<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Test</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <style>
    body {
      font-family: Arial, Helvetica, sans-serif;
    }

    .container {
      margin: 0 auto;
      max-width: 1200px;
    }

    .map {
      width: 100%;
      height: 600px;
    }

    .header {
      padding-top: 50px;
    }

  </style>
</head>

<body>
  <div class="container">
    <div class="header">
      <h1>Leaflet.canvas-icons</h1>
      <p>Leaflet plugin for displaying markers on canvas instead of DOM.</p>
      <p><input id="cbCollisionFlg" type="checkbox" checked="true">启用碰撞检测</p>
    </div>
    <div class="map" id="map"></div>
  </div>

  <script src="../dist/leaflet.canvasmarker.js"></script>
  <script>
    var map = L.map('map').setView([59.9578, 30.2987], 10);
    var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
      preferCanvas: true
    }).addTo(map);
    // 创建图层
    var ciLayer = L.canvasMarkerLayer({
      collisionFlg: true
    }).addTo(map);

    var icon = L.icon({
      iconUrl: 'img/pothole.png',
      iconSize: [20, 18],
      iconAnchor: [10, 9]
    });
    // 定义Marker
    var markers = [];
    for (var i = 0; i < 100000; i++) {
      var marker = L.marker([58.5578 + Math.random() * 1.8, 29.0087 + Math.random() * 3.6], {
        icon: icon,
        zIndex: 2
      }).bindPopup("I Am " + i);
      markers.push(marker);
    }
    // 把marker添加到图层
    ciLayer.addLayers(markers);

    let activeData;
    //定义事件
    ciLayer.addOnMouseDownListener(function (e, data) {
      if (data.length > 0) {
        activeData = data[0];
      }
      map.dragging.disable();
    });

    ciLayer.addOnMouseUpListener(function (e, data) {
      activeData = null;
      map.dragging.enable();
    });

    map.on("mousemove", function (e) {
      if (activeData) {
        activeData.data.setLatLng(e.latlng);
        ciLayer.redraw();
      }
    });

    document.getElementById("cbCollisionFlg").onchange = function (e) {
      ciLayer.setOptions({
        collisionFlg: e.target.checked
      });
    }

  </script>
</body>

</html>
